package com.guo.redis.business.hello.controller;

import com.guo.redis.business.hello.service.IDistributeLockService;
import com.guo.redis.config.lock.LockValueContainer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * 分布式锁，Redis 实现
 * @author gxy
 * @date 2021年6月28日00:00:39
 */
@RestController
@RequestMapping("/lock")
@Slf4j
public class DistributeLockController {
    @Autowired
    private IDistributeLockService distributeLockService;

    @RequestMapping("/tryLock")
    public Object tryLock(){
        long lockId = 12;
        //redis_lock:L1:12
        final String lockName = "redis_lock:L1:"+lockId;
        int i = ThreadLocalRandom.current().nextInt(10);
        String value = ""+Thread.currentThread().getId()+i;
        try {
            LockValueContainer.getInstance().saveValue(value);
            boolean b = distributeLockService.tryLock(lockName, value, 100, TimeUnit.SECONDS);
            log.info("tryLock: {}", b);
            return b;
        }catch (Exception e){
            log.error("", e);
            return false;
        }finally {
            LockValueContainer.getInstance().remove();
        }
    }
}
